package com.xxpn.controller.user;

import com.xxpn.controller.client.ClientLisen;
import com.xxpn.controller.client.ClientSend;
import org.json.simple.JSONObject;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Scanner;

public class ClientTwo {
    private static Socket socket;
    public static boolean connection_state = false;
    public static int ID;

    public static void main(String[] args){
        while (!connection_state) {
            connect();
            try {
                Thread.sleep(3000);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    private static void connect(){
        try {
            socket = new Socket("127.0.0.1", 9999);
            connection_state = true;
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            new Thread(new ClientLisen(socket)).start();
            //登录
            login(oos);
            new Thread(new ClientSend(socket,oos,Client.ID)).start();
            //   new Thread(new ClientHeart(socket,oos)).start();
        }catch (Exception e){
            e.printStackTrace();
            connection_state = false;
        }
    }

    public static void reconnect(){
        while (!connection_state){
            System.out.println("正在尝试重新链接.....");
            connect();
            try {
                Thread.sleep(3000);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    private static void login( ObjectOutputStream oos) throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("输入你的id：");
        String id = scanner.nextLine();
        Client.ID=Integer.parseInt(id);


        JSONObject object = new JSONObject();
        object.put("type","login");
        object.put("myid",id);
        oos.writeObject(object);
        oos.flush();
    }
}